package com.norma.netty.study.netty.chat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author zhangchaofeng
 * @date 2020/10/4
 * @description
 */
public class NettyGroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    //定义一个channel组，管理所有channel
    //GlobalEventExecutors是全局事件执行器
    public static final ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //连接建立事件，第一个执行的事件
    //将当前的channel加入到channelGroup
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户端上线的消息推送给其他客户端
        ChannelGroupFuture channelFutures = CHANNELS.writeAndFlush("[客户端:" + channel.remoteAddress() + "上线了]\n");
        CHANNELS.add(channel);
    }

    //断开连接,会自动将客户端channel从CHANNELS移除
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNELS.writeAndFlush(channel.remoteAddress() + "离线了");
    }

    //channel处于活动状态
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线了");
    }

    //channel处于非活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线了");
    }

    //读取数据并且转发
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取当前channel
        Channel channel = ctx.channel();
        for (Channel targetChannel : CHANNELS) {
            if (targetChannel != channel) {
                targetChannel.writeAndFlush("[用户 " + channel.remoteAddress() + "] " + msg + "\n");
            } else {
                targetChannel.writeAndFlush("send successful");
            }
        }
    }

    //发生异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
